package com.bitcat.base.ext

import android.view.LayoutInflater
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.bitcat.base.core.BaseActivity
import com.bitcat.base.core.BaseViewModel
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import kotlin.jvm.javaClass


//通过反射获取ViewModel的类型
fun <VM : BaseViewModel, VB : ViewBinding> BaseActivity<VM, VB>.initViewModel(): VM {
    //获取泛型信息
    val type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
    val clazz = type as Class<VM> //反射，有一定的开销
    return ViewModelProvider(this)[clazz] //性能非常高
}

fun <VM : BaseViewModel, VB : ViewBinding> BaseActivity<VM, VB>.initViewBinding(): VB {
    val type = javaClass.genericSuperclass as ParameterizedType
    val clazz = type.actualTypeArguments[1] as Class<VB>
    val method: Method = clazz.getMethod("inflate", LayoutInflater::class.java)
    return method.invoke(null, layoutInflater) as VB
}